#include "StdAfx.h"
#include "MachineMgr.h"
#include "Entity/Machine.h"
#include "dao/DAOFactory.h"
#include "dao/machinedao.h"


CMachineMgr::CMachineMgr(void)
{
	m_pMachineDao = CDAOFactory::GetMachineDao();
}

CMachineMgr::~CMachineMgr(void)
{
	if(m_pMachineDao)
		delete m_pMachineDao;
}




void  CMachineMgr::LoadMachineInfo()
{
	CMachine *     pMachine;

	if(m_bLoad)
		return;

	do 
	{
		if(!m_pMachineDao->GetAllMachine())
			break;
		pMachine = new CMachine;
		while(m_pMachineDao->EnumeMachine(*pMachine))
		{
			m_machineVector.push_back(pMachine);
			pMachine = new CMachine;
		}

		if(pMachine)
			delete pMachine;

	} while (FALSE);

	m_bLoad = true;

	return ;


}


void  CMachineMgr::ReLoadMachineInfo()
{
	Clear();
	LoadMachineInfo();

}

bool  CMachineMgr::AddAMachine(CMachine*  pMachine)
{

	bool bOk;
	if(pMachine == NULL)
		return false;

	do 
	{
		if(!m_pMachineDao->AddAMachine(*pMachine))
		{
			delete pMachine;
			bOk= false;
			break;
		}
		m_machineVector.push_back(pMachine);
		bOk = true;

	} while (false);


	return bOk;

}


bool  CMachineMgr::IsMachineExist(CString&  machineId)
{

	if(machineId == "")
		return false;
	MachineFinder  machineFinder;
	machineFinder.id = machineId;

	vector<CMachine*>::iterator  it = std::find_if(m_machineVector.begin(),m_machineVector.end(),machineFinder);
	if(it == m_machineVector.end())
		return false;
	return true;

	
}
void  CMachineMgr::GenerateSessionKey(CString&  strKey)
{
	int i ;
	TCHAR  lpStr[65] = {0};
	for(i=0 ; i < 64 ;i++)
	{
		lpStr[i] =65+rand()%26;
	}
	strKey = lpStr;
}

bool CMachineMgr::UpDateGroupRule(int groupID,CString& ruleId)
{

	if(groupID < 0 || ruleId == "")
		return false;

	bool bOk= false;
	vector<CMachine*>::iterator  it;

	do 
	{
		if(!m_pMachineDao->UpDateGroupRule(groupID,ruleId))
			break;
		for(it =m_machineVector.begin();it != m_machineVector.end();it++)
		{
			if((*it)->m_groupId == groupID )
			{
				(*it)->m_newRuleId = ruleId;
			}
		}
	
		bOk = true;
	}while(false);
	
	return bOk;

	
}
bool CMachineMgr::UpDateMachineRule(CMachine* pMachine)
{

	if(pMachine == NULL)
		return false;

	bool bOk= false;
	vector<CMachine*>::iterator  it;
	do 
	{
		if(m_pMachineDao->UpDateMachineRule(*pMachine))
		{
			bOk = true;
		}

	}while(false);

	return bOk;

}


bool CMachineMgr::DelAMachine(CMachine* pMachine)
{

	if(pMachine == NULL)
		return false;

	bool bOk= false;
	vector<CMachine*>::iterator  it;
	do 
	{
		if(!m_pMachineDao->DelAMachine(pMachine->m_machineID))
		{
			break;
		}
		for(it = m_machineVector.begin();it != m_machineVector.end();it++)
		{
			if((*it )== pMachine )
			{
				m_machineVector.erase(it);

				break;
			}
		}
		bOk = true;

	} while (FALSE);

	return bOk;
}


void  CMachineMgr::Clear()
{
	CMachine*  pMachine = NULL;
	while(m_machineVector.size())
	{
		pMachine = m_machineVector.back();
		m_machineVector.pop_back();
		if(pMachine)
			delete  pMachine;
	}
	m_bLoad = false;

}